package com.etoak.stock.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.etoak.stock.exception.BusinessException;
import com.etoak.stock.mapper.SysPermissionMapper;
import com.etoak.stock.mapper.SysRolePermissionMapper;
import com.etoak.stock.pojo.domin.SysPermissionDomain;
import com.etoak.stock.pojo.domin.SysPermissionTreeDomain;
import com.etoak.stock.pojo.entity.SysPermission;
import com.etoak.stock.service.PermissionService;
import com.etoak.stock.utils.IdWorker;
import com.etoak.stock.vo.req.PermissionAddVo;
import com.etoak.stock.vo.req.PermissionUpdateVo;
import com.etoak.stock.vo.resp.R;
import com.etoak.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author by 孙有泽
 * @Date 2024/11/11 13:21
 * @Description 权限管理service
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private IdWorker idWorker;
    /*
     * @author 孙有泽
     * @date 2024/11/12 13:02
     * @description 查询所有权限集合
     */

    @Override
    public R<List<SysPermissionDomain>> getAllPermission() {
        List<SysPermissionDomain> sysPermissions = sysPermissionMapper.selectAllPermission();
        if(CollectionUtil.isEmpty(sysPermissions)){
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }else{
            return  R.ok(sysPermissions);
        }
    }
    /*
     * @author 孙有泽
     * @date 2024/11/12 13:01
     * @description 添加权限时回显权限树,仅仅显示目录和菜单
     */

    @Override
    public R<List<SysPermissionTreeDomain>> getAllPermissionTree() {
        List<SysPermission> sysPermissions = sysPermissionMapper.selectAll();
        List<SysPermissionTreeDomain> sysPermissionTreeDomains = new ArrayList<>();
        sysPermissionTreeDomains.add(SysPermissionTreeDomain.builder().id(0L).title("顶级菜单").level(0).build());
        sysPermissionTreeDomains.addAll(getPermissionTree(sysPermissions,0L,1));
        return null;
    }
    /*
     * @author 孙有泽
     * @date 2024/11/13 13:01
     * @description 添加角色和角色关联权限
     */

    @Override
    public R addPermission(PermissionAddVo permissionAddVo) {
        SysPermission sysPermission = new SysPermission();
        sysPermission.setId(idWorker.nextId());
        BeanUtils.copyProperties(permissionAddVo,sysPermission);
        checkPermissionForm(sysPermission);
        int i=sysPermissionMapper.addPermission(sysPermission);
        if(i>0){
            return R.ok();
        }else{
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
    }
    /*
     * @author 孙有泽
     * @date 2024/11/13 13:00
     * @description 更新权限
     */
    @Override
    public R updatePermission(PermissionUpdateVo permissionUpdateVo) {
        SysPermission sysPermission = new SysPermission();
        BeanUtils.copyProperties(permissionUpdateVo,sysPermission);
        checkPermissionForm(sysPermission);
        int i=sysPermissionMapper.updatePermission(sysPermission);
        if(i>0) {
            return R.ok();
        }else{
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
    }
    /*
     * @author 孙有泽
     * @date 2024/11/12 21:29
     * @description 删除权限
     */
    @Override
    public R deletePermission(Long permissionId) {
      /*  int i=sysPermissionMapper.deletePermission(permissionId);
        if(i>0){
            return R.ok();
        }else{
            R.error(ResponseCode.DATA_ERROR.getMessage());
        }*/
        //1.判断当前角色是否有角色自己，有则不能删除
        int  count= sysPermissionMapper.findChildrenCountByParentId(permissionId);
        if(count>0){
            return R.error(ResponseCode.ROLE_PERMISSION_RELATION.getMessage());
        }
        //2.将角色关联的权限信息删除
        this.sysRolePermissionMapper.deleteByPermissionId(permissionId);
        SysPermission sysPermission = SysPermission.builder().id(permissionId).deleted(0).updateTime(new Date()).build();
        int i = this.sysPermissionMapper.updatePermission(sysPermission);
        if(i>0){
            return R.ok();
        }else{
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
    }
    /**
     * 检查添加或者更新的权限提交表单是否合法，如果不合法，则直接抛出异常
     * 检查规则：目录的父目录等级必须为0或者其他目录（等级为1）
     *          菜单的父父级必须是1，也就是必须是父目录，
     *          按钮的父级必须是菜单，也是是等级是3，且父级是2
     *          其他关联的辨识 url等信息也可做相关检查
     * @param vo
     */
    private void checkPermissionForm(SysPermission vo) {
        if (vo!=null || vo.getType()!=null || vo.getPid()!=null){
            //获取权限类型 0：顶级目录 1.普通目录 2.菜单 3.按钮
            Integer type = vo.getType();
            //获取父级id
            Long pid = vo.getPid();
            //根据父级id查询父级信息
            SysPermission parentPermission = this.sysPermissionMapper.selectByPrimaryKey(pid);
            if (type==1){
                if(!pid.equals("0") || (parentPermission!=null && parentPermission.getType()> 1)){
                    throw new BusinessException(ResponseCode.OPERATION_MENU_PERMISSION_CATALOG_ERROR.getMessage());
                }
            }
            else if (type==2){
                if (parentPermission==null || parentPermission.getType() !=1 ){
                    throw new BusinessException(ResponseCode.OPERATION_MENU_PERMISSION_CATALOG_ERROR.getMessage());
                }
                if (StringUtils.isBlank(vo.getUrl())){
                    throw new BusinessException(ResponseCode.OPERATION_MENU_PERMISSION_URL_CODE_NULL.getMessage());
                }
            }
            else if (type==3){
                if (parentPermission==null || parentPermission.getType()!=2){
                    throw new BusinessException(ResponseCode.OPERATION_MENU_PERMISSION_BTN_ERROR.getMessage());
                }
                else if (vo.getUrl()==null || vo.getCode()==null || vo.getMethod()==null){
                    throw new BusinessException(ResponseCode.DATA_ERROR.getMessage());
                }
            }
            else {
                throw new BusinessException(ResponseCode.DATA_ERROR.getMessage());
            }
        }else {
            throw new BusinessException(ResponseCode.DATA_ERROR.getMessage());
        }
    }

    private List<SysPermissionTreeDomain> getPermissionTree(List<SysPermission> sysPermissions, Long l, int i) {
        List<SysPermissionTreeDomain> sysPermissionTreeDomains = new ArrayList<>();
        for (SysPermission sysPermission : sysPermissions) {
            if(sysPermission.getPid().equals(l)&&sysPermission.getType().intValue()!=3){
                sysPermissionTreeDomains.add(SysPermissionTreeDomain.builder().id(sysPermission.getId()).title(sysPermission.getName()).level(i).build());
                sysPermissionTreeDomains.addAll(getPermissionTree(sysPermissions,sysPermission.getId(),i+1));
            }
        }
        return sysPermissionTreeDomains;
    }
}
